package com.easylinkin.linkappapi.airconditioner.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.airconditioner.entity.AirHostDevice;
import com.easylinkin.linkappapi.airconditioner.entity.AirconditionDevice;
import com.easylinkin.linkappapi.airconditioner.entity.AirconditionDeviceRecord;
import com.easylinkin.linkappapi.airconditioner.mapper.AirconditionDeviceRecordMapper;
import com.easylinkin.linkappapi.airconditioner.service.AirHostDeviceService;
import com.easylinkin.linkappapi.airconditioner.service.AirconditionDeviceRecordService;
import com.easylinkin.linkappapi.airconditioner.service.AirconditionDeviceService;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.elasticsearch.entity.ESconfig;
import com.easylinkin.linkappapi.elasticsearch.util.EsCalendar;
import com.easylinkin.linkappapi.openapi.dto.DatapushDTO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
public class AirconditionDeviceRecordServiceImpl extends ServiceImpl<AirconditionDeviceRecordMapper, AirconditionDeviceRecord> implements AirconditionDeviceRecordService {
    private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(AirconditionDeviceRecordServiceImpl.class);
    @Resource
    AirconditionDeviceService airconditionDeviceService;
    @Resource
    AirHostDeviceService airHostDeviceService;
    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;
    @Resource
    DeviceService deviceService;
    private ESconfig eSconfig;

    @Autowired
    public void setESconfig(ESconfig eSconfig) {
        this.eSconfig = eSconfig;
    }

    @Override
    public int batchInsert(List<AirconditionDeviceRecord> list) {
        if(list == null || list.size()<=0){
            return 0;
        }
        String tenantId=linkappUserContextProducer.getNotNullCurrent().getTenantId();
        list= list.stream().map(i->{i.setTenantId(tenantId);return i;}).collect(Collectors.toList());
        return baseMapper.batchInsert(list);
    }


    @Override
    public void separateMetering(DatapushDTO datapushDTO){
        if(StringUtils.isEmpty(datapushDTO)){
            return;
        }
        String deviceId=datapushDTO.getDevice_id();
        if(StringUtils.isEmpty(deviceId)){
            return;
        }
        //获取设备
        QueryWrapper<Device> deviceqw=new QueryWrapper<>();
        deviceqw.eq("code",deviceId);
        Device device=deviceService.getOne(deviceqw);
        if(device == null){
            return;
        }
        JSONObject jsonObject = datapushDTO.getData();
        //检测是否是主机
        QueryWrapper<AirHostDevice> qwhost=new QueryWrapper<>();
        qwhost.eq("device_id",deviceId);
        qwhost.eq("tenant_id",device.getTenantId());
        AirHostDevice airHostDevice= airHostDeviceService.getOne(qwhost);
        if(airHostDevice != null){
            //主机
            airHostDevice(jsonObject,airHostDevice,deviceId,device.getTenantId());
            return;
        }
        //检查是否存在该子设备
        QueryWrapper<AirconditionDevice> qwacd=new QueryWrapper<>();
        qwacd.eq("tenant_id",device.getTenantId());
        qwacd.eq("device_id",deviceId);
        AirconditionDevice airconditionDevice= airconditionDeviceService.getOne(qwacd);
        if(airconditionDevice != null){
            //子设备
            airconditionDevice(jsonObject,airconditionDevice,deviceId,device.getTenantId());
            return;
        }
    }

    @Override
    public IPage<AirconditionDeviceRecord> selectGroupByStatistics(Page<AirconditionDeviceRecord> page, AirconditionDeviceRecord airHostDevice) {
        airHostDevice.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return getHistoricDataFromEs(page,airHostDevice);
    }

    /***
     * 设备为子设备
     * @param jsonObject
     * @param airconditionDevice
     * @param deviceId
     */
    private  void airconditionDevice(JSONObject jsonObject,AirconditionDevice airconditionDevice,String deviceId,String tenantId){
        //检测对应主机状态
        QueryWrapper<AirHostDevice> qwhost=new QueryWrapper<>();
        qwhost.eq("device_id",airconditionDevice.getHostDeviceId());
        qwhost.eq("tenant_id",tenantId);
       AirHostDevice airHostDevice=airHostDeviceService.getOne(qwhost);
       if(HostState.ONE.state.equals(airHostDevice.getSwitchState()) || airHostDevice.getSwitchState() == null){
            //主机设备关机，或无检测状态
           return;
       }
       //检测是否存在记录
        AirconditionDeviceRecord airconditionDeviceRecord=new AirconditionDeviceRecord();
        airconditionDeviceRecord.setTenantId(tenantId);
        airconditionDeviceRecord.setAirconditionDeviceId(airconditionDevice.getDeviceId());
       List<AirconditionDeviceRecord> airconditionDeviceRecords=baseMapper.selectAllByAirconditionDeviceIdGropuBy(Arrays.asList(airconditionDevice.getDeviceId()),airconditionDeviceRecord);
        //空调模式 1--制冷 2--制热
        Integer airMode=jsonObject.getInteger("air_mode");
        //空调风速 1--低风 2--中风 3--高风 4--自动风
        Integer airWindSpeed=jsonObject.getInteger("air_wind_speed");
        //AirconditionDeviceRecord airconditionDeviceRecord=new AirconditionDeviceRecord();
        Date date=new Date();
       if(airconditionDeviceRecords == null || airconditionDeviceRecords.size()<=0){
           //不存在记录，则新增记录
           airconditionDeviceRecord.setType(airMode);
           airconditionDeviceRecord.setFanSpeed(airWindSpeed);
           airconditionDeviceRecord.setDuration(BigDecimal.ZERO);
           airconditionDeviceRecord.setCreateTime(date);
           airconditionDeviceRecord.setUpdateTime(date);
           airconditionDeviceRecord.setCompleteStatus(0);
           baseMapper.insert(airconditionDeviceRecord);
           return;
       }
       //存在记录，旧记录模式为空，更新记录，时长为0
        AirconditionDeviceRecord oldairconditionDeviceRecord=airconditionDeviceRecords.get(0);
        Integer type=oldairconditionDeviceRecord.getType();
        Integer fanSpeed=oldairconditionDeviceRecord.getFanSpeed();
        if( type== null ||  fanSpeed== null){
            airconditionDeviceRecord.setId(oldairconditionDeviceRecord.getId());
            airconditionDeviceRecord.setType(airMode);
            airconditionDeviceRecord.setFanSpeed(airWindSpeed);
            airconditionDeviceRecord.setDuration(BigDecimal.ZERO);
            airconditionDeviceRecord.setUpdateTime(date);
            airconditionDeviceRecord.setCompleteStatus(0);
            baseMapper.updateById(airconditionDeviceRecord);
            return;
        }



        Date oldUpdateDate=oldairconditionDeviceRecord.getUpdateTime();
        //检测是否是一致状态，不一致，新增记录；如果跨天，则新增记录
        if(!type.equals(airMode)  || !fanSpeed.equals(airWindSpeed)  || !DateUtil.getYYYYMMDDDate(date).equals(DateUtil.getYYYYMMDDDate(oldUpdateDate))){
            AirconditionDeviceRecord airconditionDeviceRecordNew=new AirconditionDeviceRecord();
            airconditionDeviceRecordNew.setDuration(BigDecimal.ZERO);
            airconditionDeviceRecordNew.setCreateTime(date);
            airconditionDeviceRecordNew.setUpdateTime(date);
            airconditionDeviceRecordNew.setAirconditionDeviceId(deviceId);
            airconditionDeviceRecordNew.setType(airMode);
            airconditionDeviceRecordNew.setFanSpeed(airWindSpeed);
            airconditionDeviceRecordNew.setTenantId(tenantId);
            airconditionDeviceRecordNew.setCompleteStatus(0);
            baseMapper.insert(airconditionDeviceRecordNew);
            //模式切换，状态为完成
            airconditionDeviceRecord.setCompleteStatus(1);
        }
        //更新风速持续时间
        Long duration=date.getTime() - oldairconditionDeviceRecord.getCreateTime().getTime();
        //（单位分钟）除以 （1000 * 60）,2 位小数,四舍五入
        airconditionDeviceRecord.setDuration(BigDecimal.valueOf(duration).divide(BigDecimal.valueOf(60000),2,BigDecimal.ROUND_HALF_UP));
        airconditionDeviceRecord.setId(oldairconditionDeviceRecord.getId());
        baseMapper.updateById(airconditionDeviceRecord);
    }

    /***
     * 设备为主机
     * @param jsonObject
     * @param airHostDevice
     * @param deviceId
     */
    private void airHostDevice(JSONObject jsonObject,AirHostDevice airHostDevice,String deviceId,String tenantId){
        String airSwitchStr=jsonObject.getString("air_switch");
        if(StringUtils.isEmpty(airSwitchStr)){
            return;
        }
        Integer totalEnergy=jsonObject.getInteger("total_energy");
        Date date=new Date();
        //0:关机,1:开机
        Integer airSwitch=Integer.valueOf(airSwitchStr);
        //主机开关机状态 0:关机, 1:开机
        Integer hostSwitchState=airHostDevice.getSwitchState();
        //1开机-> 0 关机
        if(HostState.TWO.state.equals(hostSwitchState) &&  HostState.ONE.state.equals(airSwitch)){
            //获取所有子设备
            AirconditionDevice airconditionDevice=new AirconditionDevice();
            airconditionDevice.setHostDeviceId(deviceId);
            airconditionDevice.setTenantId(tenantId);
            List<AirconditionDevice> airconditionDeviceList=airconditionDeviceService.getHostLowerAirconditionDeviceAll(airconditionDevice);
           if(airconditionDeviceList == null || airconditionDeviceList.size()<=0){
               return;
           }
            //修改持续时间
           List<String> ids=airconditionDeviceList.stream().map(i->i.getDeviceId()).collect(Collectors.toList());
           //根据子设备ID查询-》子设备分度记录表中时长为0的数据
            List<AirconditionDeviceRecord> airconditionDeviceRecordList=getDeviceRecordByDeviceId(ids,tenantId);

            airconditionDeviceRecordList=airconditionDeviceRecordList.stream().map(i->{
                final Long duration=date.getTime() - i.getCreateTime().getTime();
                //（单位分钟）除以 （1000 * 60）,2 位小数,四舍五入
                i.setDuration(BigDecimal.valueOf(duration).divide(BigDecimal.valueOf(60000),2,BigDecimal.ROUND_HALF_UP));
                i.setUpdateTime(date);
                i.setCompleteStatus(1);
                //其他字段不修改
                i.setCreateTime(null);
                i.setAirconditionDeviceId(null);
                i.setType(null);
                return i;
            }).collect(Collectors.toList());
            baseMapper.updateBatchSelective(airconditionDeviceRecordList,tenantId);
            // 新增记录
        }
        //修改主机状态
        UpdateWrapper<AirHostDevice> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("device_id",airHostDevice.getDeviceId());
        updateWrapper.eq("tenant_id",tenantId);
        updateWrapper.set("switch_state",airSwitch);
        updateWrapper.set("update_time",date);
        airHostDeviceService.update(updateWrapper);
    }

    public List<AirconditionDeviceRecord> getDeviceRecordByDeviceId(List<String> ids,String tenantId){
        if(ids == null ||ids.size()<=0){
            return null;
        }
        AirconditionDeviceRecord airconditionDeviceRecord=new AirconditionDeviceRecord();
        if(StringUtils.isEmpty(tenantId)){
            airconditionDeviceRecord.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        }else{
            airconditionDeviceRecord.setTenantId(tenantId);
        }
        return baseMapper.selectAllByAirconditionDeviceIdGropuBy(ids,airconditionDeviceRecord);
    }



    private  enum HostState{
        ONE(0,"关机"),
        TWO(1,"开机");
        HostState(Integer state,String name){
            this.state=state;
            this.name=name;
        }
        private Integer state;
        private String name;
    }



    public IPage<AirconditionDeviceRecord> getHistoricDataFromEs(Page pagemodel, AirconditionDeviceRecord airconditionDeviceRecord) {
        AirconditionDeviceRecord queryModel = airconditionDeviceRecord;
        Page page = pagemodel;
//        如果没有勾选要查询的属性，直接返回结果
        Assert.notNull(queryModel, "customQueryParams 不能为空");
        List<AirconditionDeviceRecord> airconditionDeviceRecordList=baseMapper.selectAllByAirconditionDeviceIdPage(page,queryModel);
        if(airconditionDeviceRecordList == null || airconditionDeviceRecordList.size()<=0){
            return new Page();
        }
       List<String> wattmeterIds=airconditionDeviceRecordList.stream().map(i->i.getWattmeterId()).distinct().collect(Collectors.toList());
        Long indexLong = 0L;
        Long sizeLong = 0L;
        Long projectId = 0L;
        Map<String,Double> positiveActiveEnergyMap=new HashMap<>();
        //获取当前用电量
        wattmeterIds.stream().forEach(i->{
            Double positiveActiveEnergy = this.getDeviceDataListFromES(i, projectId, indexLong.intValue(), sizeLong.intValue(),
                    DateUtil.getYYYYMMDDHHMMSSDate(queryModel.getQueryStartTime()),
                    DateUtil.getYYYYMMDDHHMMSSDate(queryModel.getQueryEndTime()),
                    Arrays.asList("positive_active_energy"));
            positiveActiveEnergyMap.put(i,positiveActiveEnergy);
        });
        LOGGER.info("es查询结果到设备历史用电量 ：" + positiveActiveEnergyMap);
        if(airconditionDeviceRecordList == null || airconditionDeviceRecordList.size()<=0){
            return new Page();
        }
        //获取所有QA 总和
        Double sum=airconditionDeviceRecordList.stream().map(i->{
            BigDecimal lowFan=i.getLowFan();
            if(lowFan != null){
                lowFan=lowFan.multiply(i.getLowFanDuration());
            }
            BigDecimal midFan=i.getMidFan();
            if(midFan != null){
                midFan=midFan.multiply(i.getMidFanDuration());
            }
            BigDecimal highFan=i.getHighFan();
            if(highFan != null){
                highFan=highFan.multiply(i.getHighFanDuration());
            }
            return BigDecimal.ZERO.add(lowFan).add(midFan).add(highFan);
        }).mapToDouble(BigDecimal::doubleValue).sum();
        //计算总耗能 低：lowFan，中：midFan，高：highFan
           airconditionDeviceRecordList.stream().forEach(i->{
                    //低风
                    BigDecimal lowFan=i.getLowFan();
                    if(lowFan != null){
                        lowFan=lowFan.multiply(i.getLowFanDuration());
                    }
                    //中风
                    BigDecimal midFan=i.getMidFan();
                    if(midFan != null){
                        midFan=midFan.multiply(i.getMidFanDuration());
                    }
                    //高风
                    BigDecimal highFan=i.getHighFan();
                    if(highFan != null){
                        highFan=highFan.multiply(i.getHighFanDuration());
                    }
                    //QA
                    BigDecimal totalEnergy=lowFan.add(midFan).add(highFan);
                    if(totalEnergy == null){
                        totalEnergy=BigDecimal.ZERO;
                    }
                    //QA/(QA+...QN) * 绑定的电表正向用电
                    if(totalEnergy.compareTo(BigDecimal.ZERO) != 0){
                        totalEnergy=totalEnergy.divide(BigDecimal.valueOf(sum),2,BigDecimal.ROUND_HALF_UP);
                        Double positiveActiveDB=positiveActiveEnergyMap.get(i.getWattmeterId());
                        if(positiveActiveDB == null){
                            positiveActiveDB=0.0;
                        }
                        totalEnergy=totalEnergy.multiply(BigDecimal.valueOf(positiveActiveDB));
                        i.setTotalEnergy(totalEnergy);
                    }
                    i.setBootTime(i.getLowFanDuration().add(i.getMidFanDuration()).add(i.getHighFanDuration()));
                });
        if(page == null){
            page=new Page();
        }
        page.setRecords(airconditionDeviceRecordList);
        return page;
    }

    @Override
    public void exportData(AirconditionDeviceRecord requestModel, HttpServletRequest request, HttpServletResponse response) {
        requestModel.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        //获取数据源
        List<AirconditionDeviceRecord> airHostDeviceList=getHistoricDataFromEs(null,requestModel).getRecords();

        //导出
        List<String> stringList = new ArrayList<String>();
        String keyValue = "设备名称:deviceName,低风:lowFanDuration,中风:midFanDuration,高风:highFanDuration,使用时长:bootTime,总能耗(KW·h):totalEnergy";

        String title = "分户计量列表";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportBankExcelV2(outputStream, keyValue, airHostDeviceList, ExcelConstant.XLS, title, stringList);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败");
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败");
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }


    public Double getDeviceDataListFromES(String deviceCode, Long projectId, int index, int size, String beginTime, String endTime, List<String> necessaryFieldList) {
        if(org.springframework.util.StringUtils.isEmpty(deviceCode)){
            return 0.0;
        }
        QueryBuilder boolquery = QueryBuilders.boolQuery();
        if (!CollectionUtils.isEmpty(necessaryFieldList)) {
            necessaryFieldList.forEach(item -> {
//                属性状态值 挪到了 data之下
                QueryBuilder existQuery = QueryBuilders.existsQuery("data." + item);
                ((BoolQueryBuilder) boolquery).should(existQuery);
            });
        }
        // es 6.0以上支持RestHighLevelClient
        RestHighLevelClient hclient = eSconfig.getFactory().getRhlClient();

//        获取索引,这个月和上个月的 deviceflow-202101,deviceflow-202012
        String indices = EsCalendar.getDeviceFlowIndex(2);
        SearchRequest searchRequest = new SearchRequest(indices);
        //忽略不可用索引，允许索引不不存在，通配符表达式将扩展为打开的索引
        searchRequest.indicesOptions(IndicesOptions.fromOptions(true,true,true,false));
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 查询条件，可以参考官网手册
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        Assert.notNull(deviceCode, "查询Es，设备编号不能为空!");
        boolQuery.must(QueryBuilders.matchPhraseQuery("deviceCode", deviceCode));
        boolQuery.must(boolquery);
        boolQuery.filter(QueryBuilders.rangeQuery("createTime").gte(beginTime).lte(endTime).format("yyyy-MM-dd HH:mm:ss"));
        searchSourceBuilder.query(boolQuery);

        //聚合求值
        //分组查询最大值
        TermsAggregationBuilder groupby_cteateTimeMax=AggregationBuilders
                .terms("groupby_cteateTimeMax").field("createTime")
                .order(BucketOrder.key(false))
                .size(1)
                .subAggregation(AggregationBuilders.max("createTimeMax").field("createTime"))
                .executionHint("map");
        //查询最大值所有数据
        AggregationBuilder top_score_member_Max= AggregationBuilders.topHits("top_score_member_Max");
        groupby_cteateTimeMax.subAggregation(top_score_member_Max);

        TermsAggregationBuilder groupby_cteateTimeMin=AggregationBuilders.terms("groupby_cteateTimeMin").field("createTime")
                .order(BucketOrder.key(true))
                .size(1)
                .subAggregation(AggregationBuilders.min("createTimeMin").field("createTime"))
                .executionHint("map");
        //查询最小值所有数据
        AggregationBuilder top_score_member_Min= AggregationBuilders.topHits("top_score_member_Min");
        groupby_cteateTimeMin.subAggregation(top_score_member_Min);

        //添加聚合条件
        searchSourceBuilder.aggregation(groupby_cteateTimeMax);
        searchSourceBuilder.aggregation(groupby_cteateTimeMin);
        searchSourceBuilder.trackTotalHits(true);

//        ES 本身限制 最大只能查询一万条
        searchSourceBuilder.from(0).size(0);  //取数大小
        searchSourceBuilder.sort("createTime", SortOrder.DESC); //倒叙
        searchRequest.source(searchSourceBuilder);
        long startTime = System.currentTimeMillis();
        //声明最大最小正向功率值
        Double max=null,min=null;
        //聚合求值
        Map<String,Object> map=null;
        Aggregations aggregations;
        try {
            // 查询结果
            LOGGER.info("设备数据详情ES请求数据：" + searchRequest.toString());
            SearchResponse searchResponse = hclient.search(searchRequest, RequestOptions.DEFAULT);
            aggregations=searchResponse.getAggregations();

            Terms groupby_cteateTimeTermsMax=aggregations.get("groupby_cteateTimeMax");
            List<? extends Terms.Bucket> bucketMax=groupby_cteateTimeTermsMax.getBuckets();
            for(Terms.Bucket bucket : bucketMax){
                TopHits topScoreResult  = bucket.getAggregations().get("top_score_member_Max");
                SearchHit searchHit = topScoreResult.getHits().getAt(0);
                map=searchHit.getSourceAsMap();
                if(map == null){
                    return 0.0;
                }
                //只有一条数据直接赋值
                HashMap data=(HashMap)map.get("data");
                if(data != null){
                    max=(Double) data.get("positive_active_energy");
                }
            }

            //最小
            Terms groupby_cteateTimeTermsMin=aggregations.get("groupby_cteateTimeMin");
            List<? extends Terms.Bucket> bucketMin=groupby_cteateTimeTermsMin.getBuckets();
            for(Terms.Bucket bucket : bucketMin){
                TopHits topScoreResult  = bucket.getAggregations().get("top_score_member_Min");
                SearchHit searchHit = topScoreResult.getHits().getAt(0);
                map=searchHit.getSourceAsMap();
                if(map == null){
                    return 0.0;
                }
                HashMap data=(HashMap)map.get("data");
                if(data != null){
                    min=(Double) data.get("positive_active_energy");
                }
            }

        } catch (Exception e) {
            LOGGER.error("搜索ES数据,索引:" + deviceCode + "异常:{}", e);
            return 0.0;
        } finally {
        }
        long sysEndTime = System.currentTimeMillis();
        LOGGER.info("查询用时:" + (sysEndTime - startTime));
        if(max == null || min == null){
           return 0.0;
        }
        return (max-min);
    }
}
